package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_lifestyle.bp_fragment

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.anythink.interstitial.api.ATInterstitial
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseFragment
import com.bp.hearthealth.pulse.lnapps.base.bp_liveDataBus.BpLiveDataBus
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.UIHelperBp
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_lifestyle.BpLifeStyleViewModel
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_lifestyle.bp_adapter.BpLifeStyleIndicatorAdapter
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_lifestyle.bp_adapter.BpLifeStylePagerAdapter
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_lifestyle.bp_bean.BpIndicatorDataBean
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_view.BPLeftAndRightItemDecoration
import com.bp.hearthealth.pulse.lnapps.databinding.LifestyleFragmentBgBinding
import com.google.android.gms.ads.nativead.NativeAd
import com.gyf.immersionbar.ImmersionBar
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.lang.reflect.Field
import java.util.Timer
import java.util.TimerTask


class BpLifeStyleFragment : BpBaseFragment<LifestyleFragmentBgBinding>() {

    private var nativeAd: NativeAd? = null
    private lateinit var lifeStylePagerAdapter: BpLifeStylePagerAdapter
    private val viewModel: BpLifeStyleViewModel by viewModel()
    private val lifeStyleIndicatorAdapter = BpLifeStyleIndicatorAdapter()
    private val timer = Timer()
    lateinit var viewPager2: ViewPager2

    override fun loadDataOnce() {
        super.loadDataOnce()
        binding.viewModel = viewModel
        binding.lifecycleOwner = this
        viewPager2 = binding.viewPager
        registerObserver()
        viewModel.loadData()
        removeListener()
        //页面展示
        AppsFlyerUtils.trackEvent("lifestyle_show")
    }

    override fun onResume() {
        super.onResume()
//        loadNativeAd()
        LogUtil.i("BpLifeStyleFragment onResume")
    }

    override fun onVisible() {
        LogUtil.i("BpLifeStyleFragment：更新广告")
//        loadNativeAd()
    }

    private fun removeListener() {
        timer.schedule(object : TimerTask() {
            override fun run() {
                //首次加载超过3秒不显示
                AdMobNativeAdManager.setNativeAdListener(null)
            }
        }, 3000)
    }

    /**
     * 加载原生广告
     *     ■ 原生广告资源加载到，展示广告
     *     ■ 原生广告资源未加载到，隐藏广告位
     */
    private fun loadNativeAd() {
        AdMobNativeAdManager.setNativeAdListener(object : AdMobNativeAdListener {
            override fun onAdLoaded(loadedNativeAd: MutableList<NativeAd>) {
                LogUtil.i("BpLifeStyleFragment onAdLoaded 回调")
                setNativeAdView(loadedNativeAd)
            }

            override fun onAdImpression() {
                //原生广告埋点
                AppsFlyerUtils.trackEvent("ad_native_lifestyle_show")
                ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID,"f6647206b17b61")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【Lifestyle页_原生广告】")
                AdMobNativeAdManager.removeUsedNativeAdListener()
            }
        })
        val nativeAdList = AdMobNativeAdManager.getNativeAds()
        if (nativeAdList.isNotEmpty()) {
            LogUtil.i("BpLifeStyleFragment 设置广告显示")
            setNativeAdView(nativeAdList)
        }
    }

    private fun setNativeAdView(nativeAdList: MutableList<NativeAd>) {
        nativeAd = nativeAdList.first()
        binding.nativeAdContainer.setNativeAd(nativeAd)
        binding.nativeAdContainer.visibility = View.VISIBLE
    }

    private fun registerObserver() {
        BpLiveDataBus.with<Boolean>(AdsSwitch.adAppControl).observe(this) {
            binding.nativeAdContainer.visibility = View.GONE
            AdMobNativeAdManager.release()
        }
        viewModel.allList.observe(viewLifecycleOwner, Observer { list ->
            if (list.isNullOrEmpty()) {
                return@Observer
            }
            initViewPager()
            initRecyclerView()
            viewModel.refreshTab(0)
            lifeStylePagerAdapter.updateFragments(list)
        })
        viewModel.selectedPosition.observe(viewLifecycleOwner) { position ->
            binding.viewPager.currentItem = position
        }
    }

    private fun initViewPager() {
//        resolveConflicts()
        lifeStylePagerAdapter = BpLifeStylePagerAdapter(this)
//        binding.viewPager
        binding.viewPager.adapter = lifeStylePagerAdapter
        binding.viewPager.orientation = ViewPager2.ORIENTATION_HORIZONTAL
        binding.viewPager.offscreenPageLimit = 3
        binding.viewPager.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                lifeStyleIndicatorAdapter.updateIndicator(position)
                if (position == 0) {
                    setPagingEnabled(false)
                } else {
                    setPagingEnabled(true)
                }
                binding.recyclerView.scrollToPosition(position)
            }
        })
    }

    fun setPagingEnabled(enabled: Boolean) {
        binding.viewPager.isUserInputEnabled = enabled
    }

    //解决ViewPager2嵌套WebView的滑动冲突
    private fun resolveConflicts() {
        try {
            val recyclerViewField: Field = ViewPager2::class.java.getDeclaredField("mRecyclerView")
            recyclerViewField.isAccessible = true
            val recyclerView = recyclerViewField.get(binding.viewPager)
            val touchSlopField: Field = RecyclerView::class.java.getDeclaredField("mTouchSlop")
            touchSlopField.isAccessible = true
            val touchSlop = touchSlopField[recyclerView] as Int
            //通过获取原有的最小滑动距离 *n来增加此值
            touchSlopField.set(recyclerView, touchSlop * 3)
        } catch (e: Exception) {
            LogUtil.e(e)
        }
    }

    private fun initRecyclerView() {
        lifeStyleIndicatorAdapter.setListData(
            arrayListOf(
                /*BpIndicatorDataBean(UIHelperBp.getString(R.string._life_style_news_str)),*/
                BpIndicatorDataBean(UIHelperBp.getString(R.string._blood_pressure_str)),
                BpIndicatorDataBean(UIHelperBp.getString(R.string._blood_sugar_str)),
                BpIndicatorDataBean(UIHelperBp.getString(R.string._healthy_diet_str))
            )
        )
        val layoutManager = LinearLayoutManager(activity)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        binding.recyclerView.layoutManager = layoutManager
        binding.recyclerView.adapter = lifeStyleIndicatorAdapter
        val leftMargin = resources.getDimensionPixelSize(R.dimen.life_style_list_margin_top)
        val rightMargin = resources.getDimensionPixelSize(R.dimen.life_style_list_margin_top)
        binding.recyclerView.addItemDecoration(
            BPLeftAndRightItemDecoration(
                leftMargin,
                rightMargin
            )
        )
        lifeStyleIndicatorAdapter.setOnItemClickLisener(object :
            BpLifeStyleIndicatorAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                viewModel.selected.set(true)
                viewModel.refreshTab(position)
            }
        })
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        ImmersionBar.with(this).titleBar(binding.toolbar).init()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        nativeAd?.let { AdMobNativeAdManager.removeUsedNativeAd(it) }
    }
}